<?php
/**
 * Created by PhpStorm.
 * User: Raytine
 * Date: 2019/11/29
 * Time: 15:23
 */

namespace app\api\controller\android\v10;

use app\api\model\OrderModel;
use think\Exception;
use think\Controller;
use think\Request;
use app\api\model\Authority;
use think\Db;

class Artificial extends Controller
{
    protected $us;

    public function _initialize()
    {
        $this->us = Authority::check(1);
    }

    /**
     * 日报参数
     */
    protected function day_param($max = 3)
    {
        $param = Request::instance()->post();
        if (empty($param['start_date'])) {
            r_date(null, 300, "开始时间不能为空");
        }
        if (empty($param['end_date'])) {
            r_date(null, 300, "结束时间不能为空");
        }
        $start = date("Y-m-d", strtotime($param['start_date']));
        $end   = date("Y-m-d", strtotime($param['end_date']));
        //两个时间差的天数
        $day = day_value($start, $end);
        if ($day < 0) {
            r_date(null, 300, "开始时间不能小于结束时间");
        }
        //两个时间差的月数
        $month = month_value($start, $end);
        if ($month > $max) {
            r_date(null, 300, "时间跨度不能超过" . $max . "月");
        }

        return [
            'start_date'      => $start,
            'end_date'        => $end,
            'start_timestamp' => strtotime($start . ' 00:00:00'),
            'end_timestamp'   => strtotime($end . ' 23:59:59'),
            'type'            => isset($param['type']) ? $param['type'] : 1,
            'Difference'      => isset($param['Difference']) ? $param['Difference'] : 1,
            'day'             => $day,
            'month'           => $month,
            'user_id'         => isset($param['user_id']) ? $param['user_id'] : $this->us['user_id'],
        ];
    }

    public function user_list()
    {
        $cap = db('user')->where('store_id', $this->us['store_id'])->field('reserve,user_id,username')->select();
        r_date($cap, 200);
    }

    /*
     * 材料计算
     */

    public function Cost(OrderModel $orderModel)
    {
        $order_id = Request::instance()->get('order_id');
        
        $cap      = $orderModel->ManualSettlement($order_id);

        r_date($cap, 200);
    }

    /*
     * 提交人工报价
     */
    public function category()
    {
        $data = Request::instance()->post();
        $op   = json_decode($data['company'], true);
        db()->startTrans();
        try {
            foreach ($op as $item) {
                db('capital')->where(['capital_id' => $item['projectId']])->update(['labor_cost' => $item['pri'], 'material' => $item['material'],'revised'=>1]);
                $app_user_order_capital = Db::connect(config('database.db2'))->table('app_user_order_capital')->where('capital_id', $item['projectId'])->whereNull('deleted_at')->select();

                $work_time              = array_sum(array_column($app_user_order_capital, 'work_time'));
                if ($work_time == 0) {
                    if($app_user_order_capital){
                        Db::connect(config('database.db2'))->table('app_user_order_capital')->where('capital_id', $item['projectId'])->update(['personal_price' =>0,'total_price'=>$item['pri']]);
                    }

                } else {

                    foreach ($app_user_order_capital as $value) {
                        $orderCapital = db('large_reimbursement',config('database.zong'))->where('order_id', $value['order_id'])->where('user_id',$value['user_id'])->where('status',1)->sum('money');
                        $orderCapitalMoney =db('app_user_order_capital',config('database.db2'))->where('order_id', $value['order_id'])->where('id', '<>',$value['id'])->where('user_id',$value['user_id'])->whereNull('deleted_at')->sum('personal_price');

                        if ($orderCapital>$orderCapitalMoney+sprintf('%.2f', $item['pri'] * $value['work_time'] / $work_time)) {
                            throw new Exception('过审大工地结算金额超过清单工资');
                        }

                    }

                    foreach ($app_user_order_capital as $value) {
                        if($value['work_time']==0){
                            Db::connect(config('database.db2'))->table('app_user_order_capital')->where('id', $value['id'])->update(['personal_price' =>0,'total_price'=>$item['pri']]);
                        }else{
                            Db::connect(config('database.db2'))->table('app_user_order_capital')->where('id', $value['id'])->update(['personal_price' => sprintf('%.2f', $item['pri'] * $value['work_time'] / $work_time),'total_price'=>$item['pri']]);

                        }

                    }
                }
            }
            db()->commit();

            r_date([], 200, '新增成功');
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }
    }

    //店铺成交量
    public function turnover_day(OrderModel $orderModel)
    {
        $timedata = $this->day_param(3);

        $start_timestamp = $timedata['start_timestamp'];
        // $end_timestamp = $timedata['end_timestamp'];
        $day              = $timedata['day'];
        $order_num        = [];
        $order_turnover   = [];
        $order_cost       = [];
        $material_usage   = [];
        $reimbursement    = [];
        $profit           = [];
        $order_unit_price = [];
        for ($i = $day; $i > -1; $i--) {
            $_begin = $start_timestamp + $i * 86400;
            $_end   = $start_timestamp + 86399 + $i * 86400;
            $order  = $orderModel->order_list($timedata['type'], $_begin, $_end, empty($timedata['user_id']) ? $this->us['user_id'] : $timedata['user_id'], $this->us['store_id']);

            //成交额
            $turnover         = order_for_turnover($order);
            $order_num[]      = [
                'time' => date('Y/m/d', $_begin),
                'data' => count($order),
            ];
            $order_turnover[] = [
                'time' => date('Y/m/d', $_begin),
                'data' => $turnover,
            ];

            if ($timedata['Difference'] == 4) {
                if ($turnover > 0) {
                    $unit_price = sprintf("%.2f", ($turnover / count($order)));
                } else {
                    $unit_price = 0;
                }
                $order_unit_price[] = [
                    'time' => date('Y/m/d', $_begin),
                    'data' => $unit_price,
                ];
            } elseif ($timedata['Difference'] == 5) {

                //预计人工费
                $order_cost[] = [
                    'time' => date('Y/m/d', $_begin),
                    'data' => order_for_artificial($order),
                ];
                //预计材料费
                $material_usage[] = [
                    'time' => date('Y/m/d', $_begin),
                    'data' => order_for_Finance($order),
                ];
                //报销费(只要实际报销)
                $reimbursement[] = [
                    'time' => date('Y/m/d', $_begin),
                    'data' => order_for_outlay($order),
                ];
                $profit[]        = [
                    'time' => date('Y/m/d', $_begin),
                    'data' => sprintf("%.2f", ($turnover - order_for_artificial($order) - order_for_Finance($order) - order_for_outlay($order))),
                ];

            } else if ($timedata['Difference'] == 6) {

                //实际人工费
                $order_cost[] = [
                    'time' => date('Y/m/d', $_begin),
                    'data' => order_for_reality_artificial($order),
                ];
                //实际材料费
                $material_usage[] = [
                    'time' => date('Y/m/d', $_begin),
                    'data' => order_for_reality_material($order),
                ];
                //报销费(只要实际报销)
                $reimbursement[] = [
                    'time' => date('Y/m/d', $_begin),
                    'data' => order_for_outlay($order),
                ];
                $profit[]        = [
                    'time' => date('Y/m/d', $_begin),
                    'data' => sprintf("%.2f", ($turnover - order_for_reality_artificial($order) - order_for_reality_material($order) - order_for_outlay($order))),
                ];
            }


        }
        r_date(['order_num' => $order_num, 'order_turnover' => $order_turnover, 'order_unit_price' => $order_unit_price, 'order_cost' => $order_cost, 'material_usage' => $material_usage, 'reimbursement' => $reimbursement, 'profit' => $profit], 200, '操作成功');

    }


}